package com.cheer.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.common.Page;
import com.cheer.dao.OaNoticeDao;
import com.cheer.dto.OaNoticeAddDTO;
import com.cheer.dto.OaNoticeUpdateDTO;
import com.cheer.entity.OaNoticeEntity;
import com.cheer.exception.ServiceException;
import com.cheer.service.OaNoticeService;
import com.cheer.vo.OaNoticeInfoVO;
import com.cheer.vo.OaNoticeListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("oaNoticeService")
public class OaNoticeServiceImpl extends ServiceImpl<OaNoticeDao, OaNoticeEntity> implements OaNoticeService {

    @Autowired
    private OaNoticeDao oaNoticeDao;

    @Override
    public void add(OaNoticeAddDTO noticeAddDTO) {
        OaNoticeEntity notice = new OaNoticeEntity()
                .setContent(noticeAddDTO.getContent())
                .setAddTime(String.valueOf(DateUtil.currentSeconds()));


        oaNoticeDao.insert(notice);
    }

    @Override
    public Page<OaNoticeListVO> list(Integer pageNum, Integer pageSize) {
        IPage<OaNoticeEntity> page = oaNoticeDao.selectPage(pageNum, pageSize);

        List<OaNoticeListVO> list = page.getRecords().stream()
                .map(notice -> new OaNoticeListVO()
                        .setId(notice.getId())
                        .setContent(notice.getContent())
                        .setAddTime(DateUtil.format(DateUtil.date(Long.valueOf(notice.getAddTime()) * 1000),
                                DatePattern.NORM_DATETIME_PATTERN)))
                .collect(Collectors.toList());

        return new Page<>(page, list);
    }

    @Override
    public OaNoticeInfoVO info(Integer id) {
        OaNoticeEntity notice = oaNoticeDao.selectById(id);
        if (notice == null) {
            throw new ServiceException("通知不存在");
        }

        return new OaNoticeInfoVO()
                .setId(notice.getId())
                .setContent(notice.getContent());
    }

    @Override
    public void update(OaNoticeUpdateDTO noticeUpdateDTO) {
        OaNoticeEntity notice = oaNoticeDao.selectById(noticeUpdateDTO.getId());
        if (notice == null) {
            throw new ServiceException("通知不存在");
        }

        OaNoticeEntity updateNotice = new OaNoticeEntity()
                .setId(noticeUpdateDTO.getId())
                .setContent(noticeUpdateDTO.getContent());

        oaNoticeDao.updateById(updateNotice);
    }

    @Override
    public String getFirst() {
        OaNoticeEntity notice = oaNoticeDao.getFirst();
        if (notice == null) {
            return null;
        }

        return notice.getContent();
    }
}